package com.quick.develop.flowable.framework.cmd;

import com.quick.develop.flowable.utils.BpmTaskUtil;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.cmd.NeedsActiveTaskCmd;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.HistoricTaskService;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

import java.util.Objects;

/**
 * @author junyuan.liu
 * @description: 设置任务描述，用于标记一些特殊操作
 * @date 2022/8/14 16:06
 */
public class SetTaskDescCmd extends NeedsActiveTaskCmd<Void> {
    private static final long serialVersionUID = -7138270163373358437L;
    
    protected String desc;

    public SetTaskDescCmd(String taskId, String desc) {
        super(taskId);
        this.desc = desc;
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity taskEntity) {
        HistoricTaskService historicTaskService = CommandContextUtil.getHistoricTaskService(commandContext);
        TaskService taskService = CommandContextUtil.getTaskService(commandContext);
        HistoricTaskInstanceEntity historicTask = historicTaskService.getHistoricTask(taskId);
        String newDesc = BpmTaskUtil.concatDescription(taskEntity.getDescription(), desc);
        if (!Objects.equals(newDesc, taskEntity.getDescription())) {
            taskEntity.setDescription(newDesc);
            historicTask.setDescription(newDesc);
            taskService.updateTask(taskEntity, false);
            historicTaskService.updateHistoricTask(historicTask, false);
        }
        
        return null;
    }
}
